package com.lottery.ruok.lottrey.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.LHCBetListAdapter;
import com.lottery.ruok.lottrey.bean.OrderObservableList;
import com.lottery.ruok.lottrey.eventbusObject.AddBetList;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.CreateOrderRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCurrentIssueNoRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.CreateOrderResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCurrentIssueNoResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetLotteryDetailResponse;
import com.lottery.ruok.lottrey.ui.BottomButtonModule;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import count_down.CountDownManager;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import ui.IToast;
import ui.IToastAddBet;
import utils.Utils;

/*
* 投注单
* */

public class LHCBetListActivity extends BaseActivity {

    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.delete)
    TextView delete;
    @BindView(R.id.money)
    TextView moneyAndNum;
    @BindView(R.id.time)
    TextView time;

    private LHCBetListAdapter myAdapter;
    public static OrderObservableList<Results> liuheBeanArrayList = new OrderObservableList<>();
    private BottomButtonModule mBottomButtonModule;
    public ArrayList<Integer> recordMoneyList;
    private CountDownManager.CountDownModel countDownModel;
    private GetCurrentIssueNoResponse data;
    private boolean isHttp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lhcbet_list);
        ButterKnife.bind(this);

        init();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new AddBetList());
        CountDownManager.asInstance().unRegister(countDownModel);
        super.onDestroy();

    }

    public static class Results implements Parcelable{
        public String number;//数字
        public String odd;//赔率
        public String title;//玩法的标题
        public int single;//单注价格
        public int quantity;//注数
        public int total;//总金钱
        public String rule_id;//区别玩法
        public String rakeback;//返水
        public String type;

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.number);
            dest.writeString(this.odd);
            dest.writeString(this.title);
            dest.writeInt(this.single);
            dest.writeInt(this.quantity);
            dest.writeInt(this.total);
            dest.writeString(this.rule_id);
            dest.writeString(this.rakeback);
            dest.writeString(this.type);
        }

        public Results() {
        }

        protected Results(Parcel in) {
            this.number = in.readString();
            this.odd = in.readString();
            this.title = in.readString();
            this.single = in.readInt();
            this.quantity = in.readInt();
            this.total = in.readInt();
            this.rule_id = in.readString();
            this.rakeback = in.readString();
            this.type = in.readString();
        }

        public static final Creator<Results> CREATOR = new Creator<Results>() {
            public Results createFromParcel(Parcel source) {
                return new Results(source);
            }

            public Results[] newArray(int size) {
                return new Results[size];
            }
        };
    }

    private void init() {
        recordMoneyList = new ArrayList<>();
        mBottomButtonModule = new BottomButtonModule(this,
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        if (liuheBeanArrayList.size() == 0) {
                            Utils.showToast("您的注数为0");
                        } else {
                            if (data==null){
                                Utils.showToast("稍候片刻");
                                return null;
                            }
                            if (data.getTime() < 10) {
                                Utils.showToast("已封盘");
                                return null;
                            }
                            addBet();
                        }
                        return null;
                    }
                },
                new Function1<String, Unit>() {
                    @Override
                    public Unit invoke(String s) {
                        for (Results results : LHCBetListActivity.liuheBeanArrayList.getList()) {
                            if (s.length() == 0) {
                                results.single = 0;
                            } else {
                                results.single = Integer.parseInt(s);
                            }
                            results.total = results.single * results.quantity;
                        }

                        if (myAdapter != null) {
                            myAdapter.notifyDataSetChanged();
                        }

                        setMoney();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        for(int i = 0; i < liuheBeanArrayList.size(); i++){
                            liuheBeanArrayList.getList().get(i).single = recordMoneyList.get(i);
                            liuheBeanArrayList.getList().get(i).total = liuheBeanArrayList.getList().get(i).single * liuheBeanArrayList.getList().get(i).quantity;
                        }

                        if (myAdapter != null) {
                            myAdapter.notifyDataSetChanged();
                        }

                        setMoney();
                        return null;
                    }
                });

        if(!getIntent().getBooleanExtra("shopping_car", false)) {
            ArrayList<Results> t = getIntent().getParcelableArrayListExtra("lists");
            liuheBeanArrayList.addAll(t);
        }

        for (Results results : liuheBeanArrayList.getList()) {
            recordMoneyList.add(results.single);
        }

        setTimer();


        GetLotteryDetailResponse.ColorBean colorBean = getIntent().getParcelableExtra("colors");

        myAdapter = new LHCBetListAdapter(LHCBetListActivity.this, colorBean, this, getIntent().getIntExtra("type", 0));
        listView.setAdapter(myAdapter);

        setMoney();
        countDownModel = new CountDownManager.CountDownModel() {
            @Override
            public void onExecute() {
                if (data != null) {
                    data.setTime(data.getTime() - 1);
                    if (data.getTime() >= 0) {
                        time.setText(Html.fromHtml(String.format("第%s期投注截止时间: <font color='#3f3f3f'>%s</font>", data.getNo(), Utils.getCountTimeByLong(data.getTime() * 1000))));
                    } else {
                        if (!isHttp) {
                            setTimer();
                            Utils.createDialog(LHCBetListActivity.this, "订单期数已变，是否继续下注？", "确认下注", "取消下注", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            }, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    finish();
                                }
                            });
                        }
                    }
                }
            }
        };
        CountDownManager.asInstance().register(countDownModel);
    }

    public void setMoney(){
        int count = 0;
        int money = 0;
        for(Results results : liuheBeanArrayList.getList()){
            if(results.quantity == 0){
                count++;
            } else {
                count+= results.quantity;
            }
            money += results.total;
        }
        moneyAndNum.setText(count + "注" + money + "元");
    }

    private void setTimer() {

        RetrofitBase.getRetrofit().create(GetCurrentIssueNoRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<GetCurrentIssueNoResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetCurrentIssueNoResponse>(this) {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        isHttp = true;
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        isHttp = false;
                    }

                    @Override
                    protected void _onNext(final GetCurrentIssueNoResponse getCurrentIssueNoResponse) {
                        data = getCurrentIssueNoResponse;
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @OnClick({R.id.delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.delete:
                Utils.createDialog(this, "是否要全部删除？", "是", "否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        liuheBeanArrayList.clear();

                        myAdapter.notifyDataSetChanged();

                        setMoney();
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                break;
        }
    }

    private void addBet(){
        JSONArray jsonArray = new JSONArray();
        for(Results result : liuheBeanArrayList.getList()){
            JSONObject jsonObject = new JSONObject();
            try {
                if(getIntent().getIntExtra("type", 0) == 0){
                    if(result.type != null && result.type.equals("lianwei")){
                        jsonObject.put("pick_number", result.number.replaceAll("尾", ""));
                    } else {
                        String re = result.number
                                .replaceAll("01", "1")
                                .replaceAll("02", "2")
                                .replaceAll("03", "3")
                                .replaceAll("04", "4")
                                .replaceAll("05", "5")
                                .replaceAll("06", "6")
                                .replaceAll("07", "7")
                                .replaceAll("08", "8")
                                .replaceAll("09", "9");
                        jsonObject.put("pick_number", re);
                    }

                } else if(getIntent().getIntExtra("type", 0) == 1){
                    jsonObject.put("pick_number", result.number);
                }
                if(result.single == 0){
                    Utils.showToast("单注金额不能为0");
                    return;
                } else {
                    jsonObject.put("amount_per_note", result.single);
                }

                if(result.quantity == 0){
                    jsonObject.put("note_count", 1);
                } else {
                    jsonObject.put("note_count", result.quantity);
                }
                jsonObject.put("odds", result.odd);
                jsonObject.put("rakeback", result.rakeback);
                jsonObject.put("rule_id", result.rule_id);
                jsonObject.put("is_follow", 0);
                jsonObject.put("is_win_stop", 0);
                jsonObject.put("position", "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }
        RetrofitBase.getRetrofit().create(CreateOrderRequest.class).getResult(jsonArray, UserInfo.getToken(), null)
                .compose(RxHelper.<CreateOrderResponse>handleResult())
                .subscribe(new RxSubscribe<CreateOrderResponse>(this) {
                    @Override
                    protected void _onNext(CreateOrderResponse createOrderResponse) {
                        IToastAddBet.show(getApplicationContext());
                        Utils.showToast("余额为" + createOrderResponse.getAfter_amount() + "元");

                        AddBetSuccess addBetSuccess = new AddBetSuccess();
                        addBetSuccess.setAfter_amount(createOrderResponse.getAfter_amount());
                        EventBus.getDefault().post(addBetSuccess);

                        liuheBeanArrayList.clear();

                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1){
                            IToast.show(e.getMessage(),LHCBetListActivity.this);
                        }else {
                            if (e.getMessage().equals("余额不足")){
                                Utils.createDialog(LHCBetListActivity.this, "余额不足，是否去充值？", "去充值", "取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Intent intent1 = new Intent(LHCBetListActivity.this, ChargeActivity.class);
                                        startActivity(intent1);
                                    }
                                }, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                });
                            }else {
                                IToast.show(e.getMessage(),LHCBetListActivity.this);
                            }
                        }

                    }

                    @Override
                    public boolean showDialog() {
                        return true;
                    }
                });
    }
}